//
//  CreateQRCodeViewController.swift
//  HYYWeibo
//
//  Created by HY-Mac on 16/7/14.
//  Copyright © 2016年 HY-Mac. All rights reserved.
//

import UIKit

class CreateQRCodeViewController: UIViewController {

    @IBOutlet weak var customView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let filter = CIFilter(name: "CIQRCodeGenerator")
        
        filter?.setDefaults()
        
        filter?.setValue("hysun".dataUsingEncoding(NSUTF8StringEncoding), forKeyPath: "InputMessage")
        
        guard let ciImage = filter?.outputImage else{ return }
        customView.image = createNonInterpolatedUIImageFormCIImage(ciImage, size: customView.frame.width)

        
    }

    /**
     生成高清二维码
     
     - parameter image: 需要生成原始图片
     - parameter size:  生成的二维码的宽高
     */
    private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
        
        let extent: CGRect = CGRectIntegral(image.extent)
        let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent))
        
        // 1.创建bitmap;
        let width = CGRectGetWidth(extent) * scale
        let height = CGRectGetHeight(extent) * scale
        let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
        let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent)
        
        CGContextSetInterpolationQuality(bitmapRef,  CGInterpolationQuality.None)
        CGContextScaleCTM(bitmapRef, scale, scale);
        CGContextDrawImage(bitmapRef, extent, bitmapImage);
        
        // 2.保存bitmap到图片
        let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)!
        
        return UIImage(CGImage: scaledImage)
    }


}
